package com.xz.hlx11;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private EditText editTextUsername;
    private EditText editTextPassword;
    private RadioGroup radioGroupLoginType;
    private RadioButton radioHuluxia;
    private RadioButton radioHuluxia3rd;
    private Button buttonLogin;
    private ProgressBar progressBar;
    private UserData userData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        userData = new UserData(this);
        
        // 填充用户名（如果有的话）
        fillUsernameIfAvailable();

        // 检查本地文件中是否有登录信息并尝试自动登录
        checkAndAutoLogin();

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performLogin();
            }
        });
    }

    private void initViews() {
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);
        radioGroupLoginType = findViewById(R.id.radioGroupLoginType);
        radioHuluxia = findViewById(R.id.radioHuluxia);
        radioHuluxia3rd = findViewById(R.id.radioHuluxia3rd);
        buttonLogin = findViewById(R.id.buttonLogin);
        progressBar = findViewById(R.id.progressBar);
    }
    
    private void fillUsernameIfAvailable() {
        // 如果有保存的用户名，填充到输入框
        if (userData != null && !userData.getUsername().isEmpty()) {
            editTextUsername.setText(userData.getUsername());
        }
    }

    private void checkAndAutoLogin() {
        // 添加调试信息
        boolean fileExists = userData.userDataFileExists();
        boolean hasData = userData.hasUserData();
        
        android.util.Log.d("AutoLogin", "文件存在: " + fileExists + ", 有数据: " + hasData);
        android.util.Log.d("AutoLogin", "用户名: " + userData.getUsername());
        android.util.Log.d("AutoLogin", "用户ID: " + userData.getUserId());
        android.util.Log.d("AutoLogin", "Key长度: " + userData.getUserKey().length());
        
        // 检查本地文件中是否有登录信息
        if (fileExists && hasData) {
            // 检查登录信息是否过期
            if (userData.isLoginExpired()) {
                Toast.makeText(this, "本地登录信息已过期（超过7天），请重新登录", Toast.LENGTH_LONG).show();
                userData.clearUserData();
                editTextUsername.setText("");
                return;
            }
            
            // 直接使用本地登录信息，跳过在线验证
            long saveTime = userData.getSaveTime();
            String timeInfo = "";
            if (saveTime > 0) {
                long daysSinceSave = (System.currentTimeMillis() - saveTime) / (1000 * 60 * 60 * 24);
                timeInfo = "（" + daysSinceSave + "天前保存）";
            }
            
            Toast.makeText(this, "自动登录成功！用户: " + userData.getUsername() + timeInfo, Toast.LENGTH_SHORT).show();
            startLotteryActivity();
        } else {
            // 没有本地登录信息，显示正常登录界面
            android.util.Log.d("AutoLogin", "没有本地登录信息");
            Toast.makeText(this, "请输入登录信息", Toast.LENGTH_SHORT).show();
            // 尝试填充用户名（可能有用户名但没有完整登录信息）
            fillUsernameIfAvailable();
        }
    }

    private void performLogin() {
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if (username.isEmpty()) {
            editTextUsername.setError("请输入用户名");
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError("请输入密码");
            return;
        }

        boolean isHuluxia = radioHuluxia.isChecked();

        showLoading(true);
        HuluxiaApi.login(username, password, isHuluxia, new HuluxiaApi.LoginCallback() {
            @Override
            public void onSuccess(String userId, String key) {
                runOnUiThread(() -> {
                    showLoading(false);
                    // 保存用户数据
                    userData.saveUserData(userId, key, username);
                    Toast.makeText(MainActivity.this, getString(R.string.login_success), Toast.LENGTH_SHORT).show();
                    // 跳转到抽奖界面
                    startLotteryActivity();
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(MainActivity.this, getString(R.string.login_failed) + ": " + error, Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    private void startLotteryActivity() {
        Intent intent = new Intent(this, LotteryActivity.class);
        startActivity(intent);
        finish();
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        buttonLogin.setEnabled(!show);
    }
}
